package com.zhhh.repository;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.sql.DataSource;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;

import com.zhhh.utils.JdbcUtil;

public class SqlDaoImpl implements SqlDaoCustom {

	@PersistenceContext
	private EntityManager em;

	/**
	 * 注入jdbc对象
	 */
	@Autowired
	private JdbcTemplate jdbcTemplate;

//    public SqlDaoImpl(JdbcTemplate jdbcTemplate) {
//        this.jdbcTemplate = jdbcTemplate;
//    }

	@Override
	public List<Map> listBySQL(String sql, Object... args) {
		Session session = (Session) em.getDelegate();
		org.hibernate.Query q = session.createSQLQuery(sql);
		// 查询结果转map
		q.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
		int i = 0;
		for (Object arg : args) {
			q.setParameter(i++, arg);
		}
		
		return q.list();
	}

	@Override
	public List<Map<String, String>> createTable(String sql) {
		String dropTable = "drop table tempTable";
		String createTable = "create table tempTable as " + sql;
		DataSource dataSource = jdbcTemplate.getDataSource();
		Connection conn;
		try {
			conn = dataSource.getConnection();
			boolean isnotExistsTable = JdbcUtil.isNotExistsTable(conn, "tempTable");
			if (isnotExistsTable) {
				jdbcTemplate.execute(dropTable);
			}
			jdbcTemplate.execute(createTable);
			List<Map<String, String>> columnsInfo = JdbcUtil.getColumnsInfo(conn, "tempTable");
			return columnsInfo;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;

	}

}
